package cn.iocoder.yudao.module.pay.wechat.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.iocoder.yudao.framework.business.basic.service.impl.AbstractService;
import cn.iocoder.yudao.module.api.pay.order.PayOrderApi;
import cn.iocoder.yudao.module.pay.wechat.convert.WechatOrderInfoConvert;
import cn.iocoder.yudao.module.pay.wechat.dao.WechatOrderInfoMapper;
import cn.iocoder.yudao.module.pay.wechat.mq.WechatOrderProducer;
import cn.iocoder.yudao.module.pay.wechat.pojo.po.WechatOrderInfo;
import cn.iocoder.yudao.module.pay.wechat.pojo.vo.WechatOrderInfoVO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <pre>
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 * 服务
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 * </pre>
 *
 * @author 山野羡民（1032694760@qq.com）
 * @since 2025/07/22
 */
@Service
public class WechatOrderInfoService extends AbstractService<WechatOrderInfo, WechatOrderInfoVO> {
    @Resource
    private WechatOrderInfoMapper wechatOrderInfoMapper;

    @Resource
    private WechatOrderProducer wechatOrderProducer;


    @Resource
    private PayOrderApi payOrderApi;

    @Override
    public WechatOrderInfoMapper getInjectedMapper() {
        return wechatOrderInfoMapper;
    }

    @Override
    public WechatOrderInfoVO convertToViewObject(WechatOrderInfo entity) {
        return WechatOrderInfoConvert.INSTANCE.toViewObject(entity);
    }

    public int requestSyncOrder() {
        // 因为历史数据会很多，此处只获取获取三个月前至今的订单
        LocalDateTime minDateTime = LocalDateTime.now().minusMonths(3);
        List<String> payNoList = payOrderApi.getPayNoByWeChatPayed(minDateTime);
        if (CollUtil.isEmpty(payNoList)) {
            return 0;
        }
        List<String> payNoComplete = wechatOrderInfoMapper.selectPayNoByCompleted(minDateTime);
        int count = 0;
        for (String payNo : payNoList) {
            if (CollUtil.isEmpty(payNoComplete) || payNoComplete.contains(payNo)) {
                continue;
            }
            wechatOrderProducer.sendWechatOrderInfoSyncMessage(payNo);
            count++;
            // 延时一下，避免并发请求
            ThreadUtil.safeSleep(200);
        }
        return count;
    }

    public int requestShippingOrder() {
        // 因为历史数据会很多，此处只获取获取三个月前至今的订单
        LocalDateTime minDateTime = LocalDateTime.now().minusMonths(3);
        List<String> payNoShipping = wechatOrderInfoMapper.selectPayNoByPaid(minDateTime);
        if (CollUtil.isEmpty(payNoShipping)) {
            return 0;
        }
        int count = 0;
        for (String payNo : payNoShipping) {
            wechatOrderProducer.sendWechatOrderShippingMessage(payNo);
            count++;
            // 延时一下，避免并发请求
            ThreadUtil.safeSleep(200);
        }
        return count;
    }

}
